import { taskType } from "../../../enum";
import { creepNameToObj } from "../../../tools/baseTools";
import { changeCreepRuleBytask, creepGetSource, creepGetTask } from "../../../tools/tools/creepTool";
import eventManager from "../../event/eventManager";
import { eventMap } from "../../event/eventMap";
import taskManager from "../../task/taskManager";


export default {
    /**rule运行逻辑
     * @param {Creep} creep 
     */
    run: function (creep) {
        // 任务池
        let taskPool = [taskType.needResource, taskType.repaire, taskType.build]
        creep = creepNameToObj(creep)
        if (creep.memory.state.isWorking) {
            // 执行freeman的通用工作逻辑
            let isRuning = false
            if (!isRuning) {
                // 无通用工作，那么就休眠重新去寻找任务池中的任务
                creep.memory['state']['isWorking'] = false
                // creep.memory['state']['sleep'] = true
                // creep.memory['state']['isBlock'] = false
                // eventManager.add(`${creep.name}无可用任务,进入休眠状态`, 5, eventMap.creepToSleep, { creepName: creep.name })
                // 去隔壁房间探路吧const oldRoomName = 'W1N1'; // 替换成你需要修改的房间名称
                const newRoomName = creep.memory.targetPos.roomName.replace(/([A-Za-z]+)(\d+)/g, (match, p1, p2) => {
                    const number = Number(p2); // 将匹配到的数字部分转换为整数
                    return `${p1}${number}`; // 返回新的字符串
                });
                creep.say(`闲得无聊，去看看外面`)
                creep.moveTo(25, 25, newRoomName, { visualizePathStyle: { stroke: '#90EE90', } })
            }
        } else {
            let isRuning = false
            let getTaskResult = creepGetTask(creep, taskPool)       // 只获取任务id
            let taskDeta = getTaskResult['taskDeta']
            if (getTaskResult['taskID']) {
                taskManager.getTaskByID(getTaskResult['taskID'], creep.name)
                console.log(`${creep.name}在${creep.pos.roomName}房间获取${getTaskResult['taskType']}类型的任务，任务id为：${JSON.stringify(creep.memory.currentTaskID)}`);
                switch (getTaskResult['taskType']) {
                    case taskType.needResource:      // 资源需求任务，切换到资源需求者逻辑
                    case taskType.repaire:      // 资源需求任务，切换到资源需求者逻辑
                    case taskType.build:      // 资源需求任务，切换到资源需求者逻辑
                        isRuning = changeCreepRuleBytask(creep, getTaskResult['taskID'], { taskDeta: taskDeta })
                        break;
                    default:
                        break;
                }
            }
            if (!isRuning) {
                // 无任务才进入准备逻辑
                if (creep.store.getFreeCapacity(RESOURCE_ENERGY) != 0) {
                    // console.log('freeman的背包中含量' + JSON.stringify(creep.store.getFreeCapacity(RESOURCE_ENERGY)));
                    creepGetSource({ creep: creep, room: Game.rooms[creep.memory.targetPos.roomName] })
                } else {
                    creep.memory.state.isWorking = true
                }
            }
        }
    }
}